﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using NetBay.Core.BusinessEntities;
using NetBay.Core.Silverlight.Log;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages;
using Rio.Framework.Pages.Context;
using Telerik.Windows.Data;
using Telerik.Windows.Controls;

namespace Rio.Framework.Pages.ChildWindows
{
    public partial class AlertListWindow : RadWindow
    {
        public Folder m_oFolder;
        public List<Alert> m_oAlertList;
        private QueryableCollectionView L_oSource;
        public string m_sGroupListToString;
        public bool m_bGroupRestrict = false;
        public string m_sMsgDeleteAlertConfirmation;
        public string m_sAlertNameLabel;
        public string m_sAlertDateLabel;
        public string m_sAlertToLabel;
        public string m_sAlertObjectLabel;
        public string m_sAlertStateLabel;
        public bool HasDeleted { set; get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="AlertListWindow" /> class.
        /// </summary>
        public AlertListWindow()
        {
            InitializeComponent();
            InitLabel();
            HasDeleted = false;

            this.CanMove = true;
            this.ResizeMode = Telerik.Windows.Controls.ResizeMode.NoResize;
            this.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterScreen;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AlertListWindow" /> class.
        /// </summary>
        /// <param name="l_oFolder">The l_o folder.</param>
        public AlertListWindow(Folder l_oFolder)
        {
            m_oFolder = l_oFolder;
            InitializeComponent();
            InitLabel();
            HasDeleted = false;

            this.CanMove = true;
            this.ResizeMode = Telerik.Windows.Controls.ResizeMode.NoResize;
            this.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterScreen;
        }

        /// <summary>
        /// Translation
        /// </summary>
        public void InitLabel()
        {
            buttonClose.Content = Resx.GetLabel(ResxAlert.CLOSE);
            buttonDelete.Content = Resx.GetLabel(ResxCommon.DELETE);
            m_sAlertNameLabel = Resx.GetLabel(ResxAlert.ALERT_NAME);
            m_sAlertDateLabel = Resx.GetLabel(ResxAlert.ALERT_DATE);
            m_sAlertObjectLabel = Resx.GetLabel(ResxAlert.ALERT_OBJECT);
            m_sAlertStateLabel = Resx.GetLabel(ResxAlert.ALERT_STATE);
            m_sAlertToLabel = Resx.GetLabel(ResxAlert.SEND_TO);
            m_sMsgDeleteAlertConfirmation = Resx.GetLabel(ResxAlert.DELETE_CONFIRMATION_ALERT);

            GetAlertList();
        }

        #region Selected listbox item event

        /// <summary>
        /// This method Get the group list and bind it to the grid
        /// </summary>
        /// <returns>A list of group</returns>
        private void GetAlertList()
        {
            var GetAlertListQuery = GlobalWebContext.BusinessEntitiesDomainContext.GetAllAlertOfTodayForAFolderQuery(m_oFolder.FolderTypeIdentifier, m_oFolder.Identifier);
            GlobalWebContext.BusinessEntitiesDomainContext.Load(GetAlertListQuery, OnGetAlertListQueryCallback, null);
            GridViewAlert.IsBusy = true;
        }

        /// <summary>
        /// Call back method binding the lis of group to the Grid
        /// </summary>
        /// <param name="result">List of group</param>
        public void OnGetAlertListQueryCallback(LoadOperation<Alert> result)
        {
            List<Alert> l_oAlertList = new List<Alert>(result.Entities);
            if (l_oAlertList.Count > 0)
            {
                //Init values list
                L_oSource = new QueryableCollectionView(l_oAlertList);
                GridViewAlert.ItemsSource = L_oSource;

                GridViewAlert.Columns["AlertName"].Header = m_sAlertNameLabel;
                GridViewAlert.Columns["AlertDate"].Header = m_sAlertDateLabel;
                GridViewAlert.Columns["AlertObject"].Header = m_sAlertObjectLabel;
                GridViewAlert.Columns["AlertTo"].Header = m_sAlertToLabel;
                GridViewAlert.Columns["AlertState"].Header = m_sAlertStateLabel;

                GridViewAlert.UnselectAll();
            }

            GridViewAlert.IsBusy = false;
        }

        /// <summary>
        /// Handles the Checked event of the chkSelectAll control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void chkSelectAll_Checked(object sender, RoutedEventArgs e)
        {
            GridViewAlert.SelectAll();
        }

        /// <summary>
        /// Handles the Unchecked event of the chkSelectAll control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void chkSelectAll_Unchecked(object sender, RoutedEventArgs e)
        {
            GridViewAlert.UnselectAll();
        }

        #endregion

        /// <summary>
        /// Handles the Click event of the buttonClose control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void buttonClose_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
            this.Close();
        }

        /// <summary>
        /// Handles the Click event of the buttonDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            // GridViewRow row = menu.GetClickedElement<GridViewRow>();
            List<Alert> L_oSelectedAlerts = new List<Alert>();
            if (GridViewAlert.SelectedItems != null && GridViewAlert.SelectedItems.Count > 0)
            {
                L_oSelectedAlerts.AddRange(GridViewAlert.SelectedItems.Cast<Alert>());


                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_sMsgDeleteAlertConfirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                L_oMessage.Show();

                L_oMessage.Closed += (s, ev) =>
                {
                    if (L_oMessage.Result == MessageBoxResult.Yes)
                    {
                        DeleteAlerts(L_oSelectedAlerts);
                    }
                };
            }
        }

        /// <summary>
        /// Deletes the alerts.
        /// </summary>
        /// <param name="P_oListAlert">The p_o list alert.</param>
        private void DeleteAlerts(List<Alert> P_oListAlert)
        {
            try
            {
                Dictionary<long, long> l_oAlertsToDelete = P_oListAlert.ToDictionary(l_oAlert => l_oAlert.Identifier, l_oAlert => (long)AlertEnums.StatusEnum.Deleted);

                GlobalWebContext.BusinessEntitiesDomainContext.UpdateAlert(l_oAlertsToDelete, delegate
                                                                          {
                                                                              HasDeleted = true;
                                                                              foreach (Alert l_oAlert in P_oListAlert)
                                                                              {
                                                                                  L_oSource.Remove(l_oAlert);
                                                                              }

                                                                          }, null);

            }
            catch (Exception ex)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);

                MessageBoxChildWindow L_oMessageDeleteFolder = new MessageBoxChildWindow("", "Error : " + Environment.NewLine + ex.Message,
                                                                MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessageDeleteFolder.Show();
            }
        }



    }
}

